import sys
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QWidget, QTabWidget,
                             QGroupBox, QLabel, QComboBox, QPushButton, QSpinBox,
                             QListWidget, QListWidgetItem, QMessageBox, QFormLayout,
                             QCheckBox, QSplitter)
from PyQt6.QtCore import Qt, pyqtSignal
from PyQt6.QtGui import QFont

from config_manager import get_config_manager


class ConfigWindow(QDialog):
    """Configuration window for advanced settings"""
    config_changed = pyqtSignal()
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.config_manager = get_config_manager()
        self.init_ui()
        self.load_settings()
        
    def init_ui(self):
        self.setWindowTitle("Configuration")
        self.setGeometry(200, 200, 800, 600)
        
        layout = QVBoxLayout(self)
        
        # Create tab widget
        tab_widget = QTabWidget()
        layout.addWidget(tab_widget)
        
        # Translation Settings Tab
        self.create_translation_tab(tab_widget)
        
        # Appearance Tab
        self.create_appearance_tab(tab_widget)
        
        # Presets Tab
        self.create_presets_tab(tab_widget)
        
        # Buttons
        button_layout = QHBoxLayout()
        
        save_btn = QPushButton("Save")
        save_btn.clicked.connect(self.save_settings)
        button_layout.addWidget(save_btn)
        
        apply_btn = QPushButton("Apply")
        apply_btn.clicked.connect(self.apply_settings)
        button_layout.addWidget(apply_btn)
        
        close_btn = QPushButton("Close")
        close_btn.clicked.connect(self.close)
        button_layout.addWidget(close_btn)
        
        button_layout.addStretch()
        layout.addLayout(button_layout)
        
    def create_translation_tab(self, tab_widget):
        """Create translation settings tab"""
        translation_tab = QWidget()
        layout = QVBoxLayout(translation_tab)
        
        # Model Selection
        model_group = QGroupBox("Model Settings")
        model_layout = QFormLayout(model_group)
        
        self.model_combo = QComboBox()
        model_layout.addRow("Translation Model:", self.model_combo)
        
        # Streaming Settings
        self.streaming_checkbox = QCheckBox("Enable streaming translation")
        self.streaming_checkbox.setToolTip("Show translation as it's being generated")
        model_layout.addRow(self.streaming_checkbox)
        
        layout.addWidget(model_group)
        
        # Preset Selection
        preset_group = QGroupBox("Translation Presets")
        preset_layout = QVBoxLayout(preset_group)
        
        self.preset_list = QListWidget()
        preset_layout.addWidget(self.preset_list)
        
        preset_buttons_layout = QHBoxLayout()
        
        new_preset_btn = QPushButton("New")
        new_preset_btn.clicked.connect(self.new_preset)
        preset_buttons_layout.addWidget(new_preset_btn)
        
        edit_preset_btn = QPushButton("Edit")
        edit_preset_btn.clicked.connect(self.edit_preset)
        preset_buttons_layout.addWidget(edit_preset_btn)
        
        delete_preset_btn = QPushButton("Delete")
        delete_preset_btn.clicked.connect(self.delete_preset)
        preset_buttons_layout.addWidget(delete_preset_btn)
        
        preset_buttons_layout.addStretch()
        preset_layout.addLayout(preset_buttons_layout)
        
        layout.addWidget(preset_group)
        layout.addStretch()
        
        tab_widget.addTab(translation_tab, "Translation")
        
    def create_appearance_tab(self, tab_widget):
        """Create appearance settings tab"""
        appearance_tab = QWidget()
        layout = QVBoxLayout(appearance_tab)
        
        # Theme Selection
        theme_group = QGroupBox("Color Scheme")
        theme_layout = QFormLayout(theme_group)
        
        self.theme_combo = QComboBox()
        themes = self.config_manager.get_available_themes()
        for theme_id, theme_data in themes.items():
            self.theme_combo.addItem(theme_data["name"], theme_id)
        theme_layout.addRow("Theme:", self.theme_combo)
        
        layout.addWidget(theme_group)
        
        # Font Settings
        font_group = QGroupBox("Font Settings")
        font_layout = QFormLayout(font_group)
        
        self.font_family_combo = QComboBox()
        self.font_family_combo.addItems(self.config_manager.get_available_fonts())
        font_layout.addRow("Font Family:", self.font_family_combo)
        
        self.font_size_spinbox = QSpinBox()
        self.font_size_spinbox.setRange(8, 24)
        self.font_size_spinbox.setSuffix(" px")
        font_layout.addRow("Font Size:", self.font_size_spinbox)
        
        layout.addWidget(font_group)
        
        # Preview
        preview_group = QGroupBox("Preview")
        preview_layout = QVBoxLayout(preview_group)
        
        self.preview_label = QLabel("Preview text: The quick brown fox jumps over the lazy dog")
        self.preview_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.preview_label.setMinimumHeight(80)
        self.preview_label.setStyleSheet("border: 1px solid gray; border-radius: 5px;")
        preview_layout.addWidget(self.preview_label)
        
        layout.addWidget(preview_group)
        layout.addStretch()
        
        tab_widget.addTab(appearance_tab, "Appearance")
        
    def create_presets_tab(self, tab_widget):
        """Create presets management tab"""
        presets_tab = QWidget()
        layout = QVBoxLayout(presets_tab)
        
        # Splitter for preset list and editor
        splitter = QSplitter(Qt.Orientation.Horizontal)
        layout.addWidget(splitter)
        
        # Left: Preset list
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)
        
        preset_list_group = QGroupBox("Presets")
        preset_list_layout = QVBoxLayout(preset_list_group)
        
        self.preset_list_detailed = QListWidget()
        self.preset_list_detailed.currentItemChanged.connect(self.on_preset_selected)
        preset_list_layout.addWidget(self.preset_list_detailed)
        
        list_buttons_layout = QHBoxLayout()
        
        new_preset_btn = QPushButton("New")
        new_preset_btn.clicked.connect(self.new_preset_detailed)
        list_buttons_layout.addWidget(new_preset_btn)
        
        list_buttons_layout.addStretch()
        preset_list_layout.addLayout(list_buttons_layout)
        
        left_layout.addWidget(preset_list_group)
        splitter.addWidget(left_widget)
        
        # Right: Preset editor
        right_widget = QWidget()
        right_layout = QVBoxLayout(right_widget)
        
        preset_editor_group = QGroupBox("Preset Editor")
        preset_editor_layout = QFormLayout(preset_editor_group)
        
        self.preset_name_edit = QComboBox()
        self.preset_name_edit.setEditable(True)
        preset_editor_layout.addRow("Name:", self.preset_name_edit)
        
        self.preset_desc_edit = QComboBox()
        self.preset_desc_edit.setEditable(True)
        preset_editor_layout.addRow("Description:", self.preset_desc_edit)
        
        self.preset_source_lang = QComboBox()
        self.preset_source_lang.addItems(["English", "Chinese", "French", "Spanish", "German", "Japanese"])
        preset_editor_layout.addRow("Source Language:", self.preset_source_lang)
        
        self.preset_target_lang = QComboBox()
        self.preset_target_lang.addItems(["Chinese", "English", "French", "Spanish", "German", "Japanese"])
        preset_editor_layout.addRow("Target Language:", self.preset_target_lang)
        
        self.preset_prompt_edit = QComboBox()
        self.preset_prompt_edit.setEditable(True)
        self.preset_prompt_edit.setToolTip("Custom prompt for translation")
        preset_editor_layout.addRow("Custom Prompt:", self.preset_prompt_edit)
        
        self.preset_enabled_checkbox = QCheckBox("Enabled")
        self.preset_enabled_checkbox.setChecked(True)
        preset_editor_layout.addRow("", self.preset_enabled_checkbox)
        
        editor_buttons_layout = QHBoxLayout()
        
        save_preset_btn = QPushButton("Save")
        save_preset_btn.clicked.connect(self.save_preset)
        editor_buttons_layout.addWidget(save_preset_btn)
        
        delete_preset_btn = QPushButton("Delete")
        delete_preset_btn.clicked.connect(self.delete_preset_detailed)
        editor_buttons_layout.addWidget(delete_preset_btn)
        
        editor_buttons_layout.addStretch()
        preset_editor_layout.addRow(editor_buttons_layout)
        
        right_layout.addWidget(preset_editor_group)
        splitter.addWidget(right_widget)
        
        splitter.setSizes([300, 500])
        
        tab_widget.addTab(presets_tab, "Preset Management")
        
    def load_settings(self):
        """Load current settings into UI"""
        # Load models
        self.load_models()
        
        # Load current settings
        current_theme = self.config_manager.get_current_theme_name()
        index = self.theme_combo.findData(current_theme)
        if index >= 0:
            self.theme_combo.setCurrentIndex(index)
            
        self.font_family_combo.setCurrentText(self.config_manager.get_font_family())
        self.font_size_spinbox.setValue(self.config_manager.get_font_size())
        self.streaming_checkbox.setChecked(self.config_manager.get_streaming_enabled())
        
        # Load presets
        self.load_presets()
        
        # Update preview
        self.update_preview()
        
    def load_models(self):
        """Load available models from Ollama API"""
        from ollama_client import OllamaClient
        
        self.model_combo.clear()
        
        try:
            client = OllamaClient()
            models = client.get_models()
            
            if models:
                for model in models:
                    model_name = model.get('name', 'Unknown')
                    self.model_combo.addItem(model_name)
                
                # Set the selected model if available
                current_model = self.config_manager.get_selected_model()
                if current_model:
                    index = self.model_combo.findText(current_model)
                    if index >= 0:
                        self.model_combo.setCurrentIndex(index)
            else:
                self.model_combo.addItem("No models available")
                
        except Exception as e:
            self.model_combo.addItem("Failed to load models")
            print(f"Error loading models: {e}")
        
    def load_presets(self):
        """Load presets into lists"""
        self.preset_list.clear()
        self.preset_list_detailed.clear()
        
        presets = self.config_manager.presets
        for preset in presets:
            # Simple list
            item_text = preset.name
            if not preset.enabled:
                item_text += " (disabled)"
            self.preset_list.addItem(item_text)
            
            # Detailed list
            detailed_item = QListWidgetItem(preset.name)
            if not preset.enabled:
                detailed_item.setForeground(Qt.GlobalColor.gray)
            detailed_item.setData(Qt.ItemDataRole.UserRole, preset)
            self.preset_list_detailed.addItem(detailed_item)
            
    def update_preview(self):
        """Update font preview"""
        font_family = self.font_family_combo.currentText()
        font_size = self.font_size_spinbox.value()
        
        if font_family == "System Default":
            font = QFont()
        else:
            font = QFont(font_family)
            
        font.setPointSize(font_size)
        self.preview_label.setFont(font)
        
    def on_preset_selected(self, current, previous):
        """Handle preset selection in detailed view"""
        if current is None:
            return
            
        preset = current.data(Qt.ItemDataRole.UserRole)
        if preset:
            self.preset_name_edit.setCurrentText(preset.name)
            self.preset_desc_edit.setCurrentText(preset.description)
            self.preset_source_lang.setCurrentText(preset.source_language)
            self.preset_target_lang.setCurrentText(preset.target_language)
            self.preset_prompt_edit.setCurrentText(preset.custom_prompt)
            self.preset_enabled_checkbox.setChecked(preset.enabled)
            
    def new_preset(self):
        """Create new preset"""
        QMessageBox.information(self, "Info", "Use the Preset Management tab to create new presets")
        
    def new_preset_detailed(self):
        """Create new preset in detailed editor"""
        self.preset_list_detailed.clearSelection()
        self.preset_name_edit.clearEditText()
        self.preset_desc_edit.clearEditText()
        self.preset_source_lang.setCurrentText("English")
        self.preset_target_lang.setCurrentText("Chinese")
        self.preset_prompt_edit.clearEditText()
        self.preset_enabled_checkbox.setChecked(True)
        
    def edit_preset(self):
        """Edit selected preset"""
        QMessageBox.information(self, "Info", "Use the Preset Management tab to edit presets")
        
    def delete_preset(self):
        """Delete selected preset"""
        QMessageBox.information(self, "Info", "Use the Preset Management tab to delete presets")
        
    def save_preset(self):
        """Save current preset"""
        from config_manager import TranslationPreset
        
        name = self.preset_name_edit.currentText().strip()
        if not name:
            QMessageBox.warning(self, "Error", "Please enter a preset name")
            return
            
        preset = TranslationPreset(
            name=name,
            description=self.preset_desc_edit.currentText().strip(),
            source_language=self.preset_source_lang.currentText(),
            target_language=self.preset_target_lang.currentText(),
            custom_prompt=self.preset_prompt_edit.currentText().strip(),
            enabled=self.preset_enabled_checkbox.isChecked()
        )
        
        self.config_manager.add_preset(preset)
        self.load_presets()
        QMessageBox.information(self, "Success", f"Preset '{name}' saved")
        
    def delete_preset_detailed(self):
        """Delete preset from detailed editor"""
        current_item = self.preset_list_detailed.currentItem()
        if not current_item:
            return
            
        preset = current_item.data(Qt.ItemDataRole.UserRole)
        if preset:
            reply = QMessageBox.question(
                self, "Confirm Delete",
                f"Are you sure you want to delete preset '{preset.name}'?",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
            )
            
            if reply == QMessageBox.StandardButton.Yes:
                self.config_manager.delete_preset(preset.name)
                self.load_presets()
                self.new_preset_detailed()
                
    def save_settings(self):
        """Save settings and close"""
        self.apply_settings()
        self.close()
        
    def apply_settings(self):
        """Apply current settings"""
        # Save theme
        theme_id = self.theme_combo.currentData()
        if theme_id:
            self.config_manager.set_theme(theme_id)
            
        # Save font settings
        self.config_manager.set_font_family(self.font_family_combo.currentText())
        self.config_manager.set_font_size(self.font_size_spinbox.value())
        self.config_manager.set_streaming_enabled(self.streaming_checkbox.isChecked())
        
        # Save selected model
        self.config_manager.set_selected_model(self.model_combo.currentText())
        
        # Update preview
        self.update_preview()
        
        # Emit signal for main window to update
        self.config_changed.emit()
        
        QMessageBox.information(self, "Success", "Settings applied successfully")


if __name__ == "__main__":
    from PyQt6.QtWidgets import QApplication
    
    app = QApplication(sys.argv)
    window = ConfigWindow()
    window.show()
    sys.exit(app.exec())